import React, { useEffect, useState, useRef } from 'react';
import { queryOrderDetail, queryReceiveOrderStatus, queryAllOrderList,  queryWaitEvaluateOrderList} from '@/services/order';
import { history, useDispatch, useSelector } from 'umi';
import Header from '@/components/Header/Header';
import useDebounceFn from '@/utils/useDebounceFn';
import { isEmpty } from '@/utils/common';
import numeral from 'numeral';
import { Picture, Price, SlideBox, AffixBottom, AsyncLoading, Modal, Message } from '@/design';
import { Scroll } from '@/components/Scroll/Scroll';
import Empty from '@/components/Empty/Empty';
import styles from './orderList.less';

export default function () {
  
  const [waitEvaluate, setWaitEvaluate] = useState<0 | 1>(0);
  const pageNoRef = useRef<number>(1);
  const hasMoreRef = useRef<boolean>(true);
  let userInfo = localStorage.getItem('userInfo');
  const { userId = '' } = JSON.parse(userInfo || '{}');
  const tabs = isEmpty(userInfo) ? ['全部'] : ['全部', '待評價'];
  const [orderlistDt, setOrderlistDt] = useState<any>({
    // list: [],
    // total: 0
    evaluateGiftIntegral: 0,
    integraDeductionProportion: 1,
    orderList: [],
    totalConsumeAmount: 0,
    totalSize: 0,
  });

  /** 請求全部訂單列表 */
  const fetchAllOrderList = async (refresh: boolean) => {
    if (!hasMoreRef.current) return false;
    let result: any;
    let loading = Message.loading({ content: `正在獲取${tabs[waitEvaluate]}列表…` });
    console.log('--------asa', waitEvaluate)
    if(waitEvaluate === 0) {
      result = await queryAllOrderList({
        orderStatus: 'all',
        buyerCode: localStorage.getItem('TOKEN'),
        pageNo: pageNoRef.current,
        braId: localStorage.getItem('BRAID'),
        userId
      });
    } else {
      const { userId = '' } = JSON.parse(userInfo || '{}');
      result = await queryWaitEvaluateOrderList({
        pageNo: pageNoRef.current,
        braId: localStorage.getItem('BRAID'),
        userId,
      });
    }
   

    loading.hide();
    if (!result || !result.data) return false;
    pageNoRef.current++;
    setOrderlistDt((prev: any) => {
      let newList = [...(refresh ? [] : prev.orderList), ...result.data.orderList || []]
      hasMoreRef.current = newList.length < result.data.totalSize
      return {
        orderList: newList,
        totalSize: result.data.totalSize,
        evaluateGiftIntegral: result.data.evaluateGiftIntegral,
        integraDeductionProportion: result.data.integraDeductionProportion,
      }
    })
  }

  const handleToComment = (e:any, orderId: string) => {
    console.log('點擊去評價')
    history.push(`/comment/${orderId}`)
    e.stopPropagation();
  }

  const handleToCommentDetail = (e:any, orderId: string) => {
    console.log('點擊去評價')
    history.push(`/comment-detail/${orderId}`)
    e.stopPropagation();
  }

  const linkToDetail = (item: any) => {
    console.log('去detail', item);
    const { orderStatus, orderId } = item;

    if(orderStatus === 'invalid'){
      return Message.error('訂單已取消');
    }

    return history.push(`/orderdetail?orderNo=${orderId}`);
  }

  const renderCommentCard = (item: any) => {
    if (item.orderStatus === 'payed') {
      if(!item.hasEvaluate) {
        return (
          orderlistDt.evaluateGiftIntegral > 0 ?
          <div className={styles.order_card_footer_comment}>
            <div className={styles.comment_inner}>
            <div>
              <span>評價得{orderlistDt.evaluateGiftIntegral}ume積分，支付可抵現</span>
              <span className={styles.to_comment} onClick={(e: any)=>{handleToComment(e, item.orderId)}}><i className={styles.edit_icon}></i>立即評價</span>
            </div>
            <p>1ume積分=NT${orderlistDt.integraDeductionProportion} </p>
          </div>
        </div> : <div className={styles.order_card_footer_comment}><div className={`${styles.comment_inner} ${styles.comment_btn}`} onClick={(e: any)=>{handleToComment(e, item.orderId)}}>
          <span className={styles.to_comment}><i className={styles.edit_icon}></i>立即評價</span>
        </div></div>
        )
      } else {
        return (
          <div className={styles.order_card_footer_comment} onClick={(e: any)=>{handleToCommentDetail(e, item.orderId)}}>
             <div className={styles.comment_inner}>
              <div>
                <span>星级</span>
                <span className={`${styles.to_comment} ${styles.hasMore}`}>查看详情</span>
              </div>
              <p>1ume積分=NT${orderlistDt.integraDeductionProportion} </p>
            </div>
          </div>
        )
      }
    } 
  }

  useEffect(() => {
    pageNoRef.current = 1;
    hasMoreRef.current = true;
    fetchAllOrderList(true)
  }, [waitEvaluate])

  // 渲染單個card
  const renderOrderCard = (item: any, index: number) => {
    const descTypes = new Map([['togoCash','提交成功請到店後支付取餐'], ['togoBespeak','提交成功請按時到店取餐'], ['togo','提交成功請稍後取餐']]);
    const classTypes = new Map([['nopay', 'nopay'], ['invalid', 'cancel'], ['unconfirm', 'unconfirm'], ['confirmed', 'confirmed'],['blankout', 'blankout'], ['payed', 'payed']]);
    const statusTypes = new Map([['nopay', '未支付'], ['invalid', '已取消'], ['unconfirm', '未確認'], ['confirmed', '已確認'],['blankout', '已作廢'], ['payed', '已支付']]);

    return (<div className={styles.order_card} key={item.orderId} style={{ animationDelay: `${index % 10 / 10}s` }} onClick={() => linkToDetail(item)}>
    <div className={styles.order_card_title}>
      {!isEmpty(descTypes.get(item.diningWay)) ? descTypes.get(item.diningWay) : '提交成功後請勿更換座位'}
    </div>
    <div className={styles.order_card_content}>
      <div>
        <strong><span>桌台號：{item.tableCode}</span></strong>
        <span className={`order_status_${classTypes.get(item.orderStatus)}`}>{statusTypes.get(item.orderStatus)}</span>
      </div>
      <div>
        <strong>
          <span>消費金額：</span>
          <span >
            <i className={styles.price}><Price price={item.orderAmount}/></i>
            {
              item.integralDeductionCash > 0 &&
              <i className={styles.price_desc}>（包含 {item.integralDeductionCash} ume積分抵扣）</i> 
            }
          </span>
        </strong>
        
      </div>
    </div>
    <div className={styles.order_card_footer}>
      <div className={styles.order_card_footer_order_info}>
        <span>訂單號：{"******" + (item.orderId && item.orderId.slice(-5))}</span>
        <span>{item.formatCreateTime}</span>
      </div>
      {/* 评论的card */}
      {!isEmpty(userId) && item.orderStatus === 'payed' && renderCommentCard(item)}
    </div>

  </div>)
  }

  console.log('232', orderlistDt);

  return (
    <>
      <Header hasBack title={'所有訂單'}></Header>
        <div className={styles.orderlist_tab}>
          {tabs.map((item, index) => <span
            key={index}
            className={waitEvaluate === index ? styles.active : ''}
            onClick={() => { setWaitEvaluate(index as (0 | 1)) }}
          >{item}</span>)}
        </div>
      
      <Scroll hasMore={hasMoreRef.current} onPullingUp={fetchAllOrderList}>
        <div className={styles.tab_hidden}></div>
        {
        !isEmpty(orderlistDt.orderList) && orderlistDt.orderList.length > 0 ? orderlistDt.orderList.map((item: any, index: number) => {
          return renderOrderCard(item, index)
        } ) : <Empty/>}
      </Scroll>
    </>
  )
}